﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Objects;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using VideoClubGorbea.Common.Interfaces;
using VideoClubGorbea.Infraestructure;
using VideoClubGorbea.Model;
using VideoClubGorbea.TheMovieDbServices;
using VideoClubGorbea.Common;
using VideoClubGorbea.Common.Utils;

namespace VideoClubGorbea.ServicesClassLibrary
{
    public class MovieServices : IMovieServices
    {
        protected IVIdeoClubGorbeaContext Context { get; set; }
        public MovieServices(IVIdeoClubGorbeaContext context)
        {
            Context = context;
        }
         public List<Movie> SearchMovies(string title)
        {
            using (Context)
            {
                var result = Context.Movies.Where(x => x.Title.Contains(title)).ToList();
                if (result.Count == 0)
                {
                    MovieDbServices movieDbServices = new MovieDbServices();
                    result =  movieDbServices.SearchMovie(title).Result.ToList();
                    result.ForEach(x =>
                    {
                        if (!Context.Movies.Any(z => z.Title == title))
                        {
                            Context.Save<Movie>(x);
                        }
                    });
                    Context.SaveChanges();                    
                }
                return result;
            }
        }

         public List<Movie> GetLatestMovies(int? page)
        {
            const int pageSize = 10;
            using (Context)
            {
                return  Context.Movies.OrderBy(x => x.ReleaseDate).Skip(page ?? 0).Take(pageSize).Include(x=>x.Posters).ToList();
            }
        }

         public Movie GetMovieById(int? id)
        {
            const int pageSize = 10;
            using (Context)
            {
                return  Context.Movies.Where(x => x.MovieID == id).Include(x=>x.Posters).FirstOrDefault(); 
            }
        }


     
    }
   
}
